
package socketsudp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author epulapp
 */
public class Client extends Thread {
    
    private DatagramSocket s;
    InetAddress addr; 
    int port;
        
    public static void main(String[] args) throws SocketException, UnknownHostException, IOException {
        new Client(InetAddress.getLocalHost(), 8080).start();
    } // main()
    
    public Client(InetAddress addr, int port) throws SocketException, UnknownHostException {
        this.s = new DatagramSocket();
        this.addr = addr;
        this.port = port;
    } // Client()
    
    @Override
    public void run() {
        
        byte[] b = new byte[8186];
        BufferedReader sysIn = new BufferedReader(new InputStreamReader(System.in));
        String strRead = "";
        
        while (!strRead.equals("END")) {
            
            //Emission
            System.out.print("Message à envoyer : ");
            try {
                strRead = sysIn.readLine();
                System.out.println("Message envoyé : " + strRead);
                b = strRead.getBytes();
            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            DatagramPacket p = new DatagramPacket(b, b.length, addr, port);
            try {
                s.send(p);
            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            //Reception
            byte[] data = new byte[8192];
            DatagramPacket r = new DatagramPacket(data, data.length);
            try {
                s.receive(r);
                addr = r.getAddress();
                port = r.getPort();
            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            String str;
            try {
                str = new String(r.getData(), "ASCII");
                str = str.trim();
                System.out.println("Message reçus : " + str + "\n");
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } // run()
    
} // Client
